package com.yzpass.api.common;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author junfeng
 */
@Getter
@Setter
public class Result<T> implements Serializable {

    public static final String SUCCESS = "success";
    // == 0 表示成功
    public static final int CODE_SUCCESS = 0;
    // > 0 表示警告
    public static final int CODE_WARN = 1;
    // <0 表示错误
    public static final int CODE_ERROR = -1;

    private int code;
    private String message;
    private T data;
    private long total;
    private String detail;

    public Result() {}
    public static <T> Result<T>  newInstance(int code,String message, T t,long total, String detail) {
        Result<T> result = new Result();
        result.setCode(code);
        result.setMessage(message);
        result.setDetail(detail);
        result.setData(t);
        result.setTotal(total);
        return result;
    }
    public static <T> Result<T> success() {
        return newInstance(CODE_SUCCESS,SUCCESS,null,0,null);
    }
    public static <T> Result<T>  success(T t) {
        return success(t,0L);
    }

    public static <T> Result<T> success(T t,Long total) {
        return newInstance(CODE_SUCCESS,SUCCESS,t,total,null);
    }

    public static <T> Result<T> error(String message) {
        return error(message,"");
    }
    public static <T> Result<T> error(String message,String detail) {
        return newInstance(CODE_ERROR,message,null,0,detail);
    }

    public static <T> Result<T> error(String message,Throwable throwable) {
        String detail = Arrays.stream(throwable.getStackTrace()).map(StackTraceElement::toString).collect(Collectors.joining("\n"));
        return error(message,detail);
    }
    public static <T> Result<T> error(Throwable throwable) {
        return error(throwable.getMessage(),throwable);
    }

    public static <T> Result<T> error(int code, String message) {
       return error(code,message,"");
    }
    public static <T> Result<T> error(int code, String message,String detail) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        result.setDetail(detail);
        return result;
    }


    public static <T> Result<T> warn(String message) {
        return warn(message,"");
    }
    public static <T> Result<T> warn(String message,String detail) {
        return newInstance(CODE_WARN,message,null,0,detail);
    }

    public static <T> Result<T> warn(String message,Throwable throwable) {
        String detail = Arrays.stream(throwable.getStackTrace()).map(StackTraceElement::toString).collect(Collectors.joining("\n"));
        return warn(message,detail);
    }
    public static <T> Result<T> warn(Throwable throwable) {
        return warn(throwable.getMessage(),throwable);
    }

}
